package org.ruanjj.net;

import org.junit.Test;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class UDPMain {
    @Test
    public void client() throws IOException {
        DatagramSocket socket = new DatagramSocket();
        byte[] b = "客户端发送数据".getBytes(StandardCharsets.UTF_8);
        InetAddress inet = InetAddress.getLocalHost();
        int port = 9090;
        DatagramPacket p = new DatagramPacket(b,b.length,inet,port);
        socket.send(p);
        socket.close();
    }

    @Test
    public void server() throws IOException {
        int port = 9090;
        DatagramSocket socket = new DatagramSocket(port);
        byte[] res = new byte[1024*64];
        DatagramPacket p = new DatagramPacket(res, res.length);
        socket.receive(p);
        String txt = new String(p.getData(),0,p.getLength());
        System.out.println(txt);
    }
}
